/*
 * @Description: 层级组件
 * @Author: Rfan
 * @Date: 2022-06-21 10:25:48
 * @LastEditTime: 2022-09-16 19:11:45
 */

import { ReactNode, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import { useSize } from 'ahooks';
import { LevelTableContextProvider, useLevelTableContext } from './contexts/LevelTableContext';
import LevelTitle from './componentes/LevelTitle';
import LevelTableList from './componentes/LevelTableList';
import styles from './styles/levelTable.module.scss';

const cx = classNames.bind(styles);

interface IDataLevelTableProps {
  data: any;
  upper?: any;
  title: ReactNode;
  onChange?: (list: any[]) => void;
}

const DataLevelTableComp = (props: IDataLevelTableProps) => {
  const { data, title, upper, onChange } = props;
  const { initInfo, setListHeight, setChangeMethod } = useLevelTableContext();

  useEffect(() => {
    if (data) {
      initInfo({ data, upper });
    }
  }, [data]);

  useEffect(() => {
    if (onChange) {
      setChangeMethod(onChange);
    }
  }, [onChange]);

  const tableWrapRef = useRef(null);
  const tableWrapSize = useSize(tableWrapRef);
  useEffect(() => {
    if (tableWrapSize?.height) {
      const operateHeight =
        tableWrapRef.current?.getElementsByClassName(cx('level-operate'))[0]?.clientHeight || 0;
      console.log('height', tableWrapSize.height, operateHeight);
      setListHeight(tableWrapSize.height - operateHeight - 45);
    }
  }, [tableWrapSize?.height]);

  return (
    <>
      <div ref={tableWrapRef} className={cx('level-table-wrap')}>
        <LevelTitle title={title} />
        <LevelTableList upper={data} />
      </div>
    </>
  );
};

const DataLevelTable = (props: IDataLevelTableProps) => (
  <LevelTableContextProvider>
    <DataLevelTableComp {...props} />
  </LevelTableContextProvider>
);

export default DataLevelTable;
